import express, { query } from "express"
const app = express()

app.use("*", (req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*")
    res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With")
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS")
    next()
})

app.get('/sse', (req, res) => {
    // 设置响应头 text/event-stream 表示使用SSE后端主动发送消息
    res.setHeader('Content-Type', 'text/event-stream')
    // 设置响应头 Cache-Control 表示不缓存
    res.setHeader('Cache-Control', 'no-cache')
    // 设置响应头 Connection 表示保持连接
    res.setHeader('Connection', 'keep-alive')

    let data = {
        query: req.query,
        time: null,
        index: 0
    }

    // 每隔1秒发送一次事件
    setInterval(() => {
        data.time = new Date().toLocaleString().replace(/\//g, '-')
        data.index++
        res.write(`data: ${JSON.stringify(data)}\n\n`)
    }, 1000)
})

app.listen(3000, () => {
    console.log('Server is running on port 3000')
})